from pydantic_settings import BaseSettings
from typing import Optional
import os
import multiprocessing
from datetime import timedelta

class Settings(BaseSettings):
    """应用配置类"""
    # 应用配置
    app_name: str = "课程表后端服务"
    debug: bool = True
    log_level: str = "INFO"
    host: str = "0.0.0.0"
    port: int = 8000
    
    # 数据库配置
    postgres_user: str = ""
    postgres_password: str = ""
    postgres_db: str = ""
    postgres_host: str = ""
    postgres_port: int = 5432
    
    # 数据库连接池配置
    db_pool_size: int = multiprocessing.cpu_count() * 2
    db_max_overflow: int = 20
    db_pool_timeout: int = 30
    db_pool_recycle: int = 1800
    
    # 数据库心跳检测配置
    db_heartbeat_enabled: bool = True
    db_heartbeat_interval: int = 300
    
    # 数据库重连配置
    db_reconnect_enabled: bool = True
    db_reconnect_max_retries: int = 3
    db_reconnect_retry_interval: int = 5
    
    # Redis配置
    redis_host: str = "localhost"
    redis_port: int = 6379
    redis_db: int = 0
    redis_password: Optional[str] = None
    redis_pool_size: int = 20
    
    # 缓存配置
    cache_ttl_default: int = 300
    cache_ttl_short: int = 60
    cache_ttl_medium: int = 600
    cache_ttl_long: int = 3600
    
    # JWT配置
    secret_key: str = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
    algorithm: str = "HS256"
    access_token_expire_minutes: int = 360
    
    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = False
    
    @property
    def database_url(self) -> str:
        """构建PostgreSQL数据库连接URL"""
        return (
            f"postgresql+asyncpg://{self.postgres_user}:{self.postgres_password}"
            f"@{self.postgres_host}:{self.postgres_port}/{self.postgres_db}"
        )
    
    @property
    def redis_url(self) -> str:
        """构建Redis连接URL"""
        auth = f":{self.redis_password}@" if self.redis_password else ""
        return f"redis://{auth}{self.redis_host}:{self.redis_port}/{self.redis_db}"
    
    @property
    def access_token_expires(self) -> timedelta:
        """获取JWT令牌过期时间"""
        return timedelta(minutes=self.access_token_expire_minutes)

# 全局配置实例
settings = Settings()
